package com.zszedu.web.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zszedu.YlbWebappApplication;
import com.zszedu.constants.RedisKeyConstants;
import com.zszedu.vo.ALYSmsResult;
import com.zszedu.vo.SmsResult;
import com.zszedu.web.config.JDWXSMSConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.aliyun.tea.*;
import com.aliyun.dysmsapi20170525.*;
import com.aliyun.dysmsapi20170525.models.*;
import com.aliyun.teaopenapi.*;
import com.aliyun.teaopenapi.models.*;
import com.aliyun.teautil.*;
import com.aliyun.teautil.models.*;

@RestController
@RequestMapping("sms")
public class SMSController {

    @Autowired
    private JDWXSMSConfig jdwxsmsConfig;


    @Autowired
    private RedisTemplate redisTemplate;


    //模拟发送短信
    @GetMapping("reg/{phone}")
    public Object index(@PathVariable String phone) throws Exception {
        redisTemplate.setKeySerializer(new StringRedisSerializer());

        //使用工具类,连接该短信接口！！！
        HashMap<String, String> params = new HashMap<>();
        //传入指定参数
        params.put("mobile",phone);//前端传入的手机号
        String temp = Math.random() + "";//随机生成一个小数 0 ~ 1,将其转换成一个字符串
        String code = temp.substring(2, 6);//截取小数后 4 位数，作为验证码

        //短信内容,必须以【】开头:    【创信】你的验证码是：%s，3分钟内有效！  %s = 等待替换值
        // 例如 String.format("123%s456", "abc"); ===> 123abc456
        String content = "【创信】您的本次的验证码是：%s";
        content = String.format(content, code);
        params.put("content",content);

        //返回固定数据
        String result = "{\"code\":\"10000\",\"charge\":false," +
                "\"remain\":0,\"msg\":\"查询成功\"," +
                "\"result\":{\"ReturnStatus\":" +
                "\"Success\",\"Message\":\"ok\",\"RemainPoint\":852969,\"TaskID\":81595483,\"SuccessCounts\":1}," +
                "\"requestId\":\"db6519c2919849bca02d3de301b250a1\"}";

        //将固定值 result 通过 objectMapper 给 SmsResult类中的属性一一对应赋值
        ObjectMapper objectMapper = new ObjectMapper();
        SmsResult smsResult = objectMapper.readValue(result, SmsResult.class);
        Map<String, String> resultMap = smsResult.getResult();
        String status = resultMap.get("ReturnStatus");
        // Success是成功的意思，当短信接口返回的不上该单词则，发送短信失败
        if ("Success".equals(status)) {//百分之百会进入，因为值以及固定了
            //发送前将验证码和手机号存入Redis中，防止用户在获取验证码后，更改手机号信息
            ValueOperations valueOperations = redisTemplate.opsForValue();
            //使用手机号当作Key值，验证码当作Value值
            valueOperations.set(String.format(RedisKeyConstants.SMS_REG, phone), code, 120, TimeUnit.SECONDS);
            return code;
        }
        return null;
    }

    //真实发送短信  需要上 https://usercenter2.aliyun.com/home 阿里云的访问控制中将权限打开！！！！！！！！！
/*    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }



    //发送短信
    @GetMapping("reg/{phone}")
    public Object index(@PathVariable String phone) throws Exception {

        String result = null;
        //随机生成一个小数 0 ~ 1,将其转换成一个字符串
        String temp = Math.random() + "";
        //截取小数后 4 位数，作为验证码
        String code = temp.substring(2, 6);

        java.util.List<String> args = java.util.Arrays.asList(YlbWebappApplication.args_);

        com.aliyun.dysmsapi20170525.Client client = SMSController.
                createClient(jdwxsmsConfig.getAccessKeyId(), jdwxsmsConfig.getAccessKeySecret());
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName("阿里云短信测试")
                .setTemplateCode("SMS_154950909")
                .setPhoneNumbers("17608977941")
                .setTemplateParam("{\"code\":\""+code+"\"}");
        RuntimeOptions runtime = new RuntimeOptions();

        try {
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
            SendSmsResponseBody body = sendSmsResponse.getBody();
            //将 接口返回的结果 通过 objectMapper 给 ALYSmsResult 类中的属性一一对应赋值
            ObjectMapper mapper = new ObjectMapper();
            result = mapper.writeValueAsString(body);
            ALYSmsResult alySms = mapper.readValue(result, ALYSmsResult.class);
            alySms.setVerification(code);
            System.out.println(alySms);
            System.out.println(alySms);

            // cede = OK 短信才会发送成功，发送成功后存储在Redis中
            if ("OK".equals(alySms.getCode())){
                redisTemplate.setKeySerializer(new StringRedisSerializer());
                //发送前将验证码和手机号存入Redis中，防止用户在获取验证码后，更改手机号信息
                ValueOperations valueOperations = redisTemplate.opsForValue();
                //使用手机号当作Key值，验证码当作Value值
                valueOperations.set(String.format(RedisKeyConstants.SMS_REG, phone), alySms, 120, TimeUnit.SECONDS);
                return alySms;
            }
        } catch (TeaException error) {
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        }

        return null;
    }*/

}
